from django.conf import settings

from django.shortcuts import render

# Create your views here.
from random import randint
import pickle, base64
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from users.models import User
from rest_framework.generics import GenericAPIView, UpdateAPIView, CreateAPIView, RetrieveAPIView

# from sms import CCP
from users.serializers import UserSerializer, VerifyEmailSerializer, AddUserHistorySerializer
from meiduo17.utils.exceptions import logger
from celery_tasks.sms import tasks as sms_tasks
from . import serializers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from goods.serializers import SKUSerializer
from carts.utils import merge_cart_cookie_to_redis


class SMSCodeView(APIView):
    def get(self, request, mobile):
        # 接收前端发送过来的数据
        # 验证手机号的格式是否正确
        # 省略　因为在前端发送到后台的时候已经验证过数据
        # 将生成的验证码放在redis中: sms_code_手机号
        # 为了预防有黑客用一个手机号一直往后台发送短信 ,所以要判断该手机号是否在短时间发送过
        # 连接数据库 verify是选择的哪款数据库
        conn = get_redis_connection('verify')
        # 如果数据库中有这个手机号的值,证明60秒内发送过信息
        sms_flag = conn.get('send_flag_%s' % mobile)
        if sms_flag:
            return Response({'message': '发送短信过于频繁'}, status=404)
        # 生成短信验证码
        sms_code = "%06d" % randint(0, 999999)
        logger.debug(sms_code)
        # conn = get_redis_connection('verify')

        pl = conn.pipeline()

        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)
        pl.execute()
        sms_code_expires = '5'
        sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)

        # 给前端返回一个响应，告诉前端验证码已经发送成功
        return Response({'message': 'ok'})


class UsernameView(APIView):
    def get(self, request, username):
        # 获取数据

        # 判断数据库中有没有这个数据
        count = User.objects.filter(username=username).count()
        # 如果count != 0 证明数据库中有数据,要返回用户名已经存在
        if count != 0:
            return Response({'message': '用户名已经存在'})
        # 如果数据库中没有这个数据 则可以给前端返回username和count
        return Response({
            'username': username,
            'count': count
        })


class MobileView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        if count != 0:
            return Response({'message': '手机号已被注册过'})
        return Response({
            'mobile': mobile,
            'count': count
        })


class UserView(CreateAPIView):
    """
    通过post把数据提交上来
    username   str
    password   str
    password2  str
    sms_code   str
    mobile     str
    allow      str  所以不能设置为bool类型
    """
    serializer_class = UserSerializer


"""
请求方式 get /user/
id	            int	    是	用户id
username	    str	    是	用户名
mobile	        str	    是	手机号
email	        str	    是	email邮箱
email_active	bool	是	邮箱是否通过验证
"""


class UserDetailView(RetrieveAPIView):
    """用户详情"""

    serializer_class = serializers.UserDeatilSerialier
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.UserEmailSerializser

    def get_object(self, *args, **kwargs):
        return self.request.user


class VerifyEmailView(GenericAPIView):
    serializer_class = VerifyEmailSerializer

    # 获取用户数据
    def get(self, request):
        data = request.query_params
        # print('解密前:',data)
        # 数据验证
        serializer = self.get_serializer(data=data)
        serializer.is_valid()
        # 更新用户邮箱状态
        data = serializer.validated_data['data']
        id = data['id']
        username = data['username']
        try:
            user = User.objects.get(id=id)
        except:
            return Response({'errors': '用户不存在'})

        user.email_active = True
        user.save()

        return Response({'email_active': True})


class AddUserHistoryView(CreateAPIView):
    serializer_class = AddUserHistorySerializer
    permission_classes = [IsAuthenticated]

    # 当用户点击用户中心会发送get请求
    def get(self, request):
        # request中有user
        user_id = request.user.id

        conn = get_redis_connection('history')
        history = conn.lrange('history_%s' % user_id, 0, 4)

        skus = []
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        ser = SKUSerializer(skus, many=True)
        return Response(ser.data)


class UserAuthorizeView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # 参考父类获取user方法
            user = serializer.object.get('user') or request.user
            response = merge_cart_cookie_to_redis(request,response,user)

        return response
